﻿using System;
using Missbot.Common;
using Missbot.Service;
using MongoDB.Bson.Serialization.Attributes;

namespace Missbot.AIModule
{
    public class DailyLimitRecord : DbBaseEntity
    {
        public string UserID { get; init; }

        public string Command { get; init; }

        public int AlreadyTimes { get; set; }

        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime ExpiryTime { get; set; }
    }

    public static class DailyLimitDA
    {
        public static DailyLimitRecord Get(string UserID, string Command)
        {
            var record = MongoService<DailyLimitRecord>.GetOnly(p => p.UserID == UserID && p.Command == Command);
            if (record != null)
            {
                return record;
            }

            record = new DailyLimitRecord {UserID = UserID, Command = Command, ExpiryTime = CommonUtil.UntilTommorow()};
            MongoService<DailyLimitRecord>.Insert(record);

            return record;
        }

        public static void Update(this DailyLimitRecord entity)
        {
            MongoService<DailyLimitRecord>.Update(entity);
        }

        public static bool Check(this DailyLimitRecord entity, int LimitTimes)
        {
            return entity.AlreadyTimes < LimitTimes;
        }

        public static void Cache(this DailyLimitRecord entity)
        {
            entity.AlreadyTimes++;
        }

        public static void Decache(this DailyLimitRecord entity, int count = 1)
        {
            entity.AlreadyTimes -= count;
        }
    }
}